import { searchRoute } from "@/utils/util";
import { Navigate, useLocation } from "react-router-dom";
import { rootRouter } from "@/routers/index";
import { store } from "@/redux";

/** 路由守卫组件 */
const AuthRouter = (props: { children: JSX.Element }) => {
    // 获取路由信息
    const { pathname } = useLocation();
    console.log(pathname);
    
    // const route = searchRoute(pathname, rootRouter);
    // console.log("route", route);
    
    // 在跳转路由之前，清除所有的axios请求
    // axiosCanceler.removeAllPending();

    // 判断是否有Token
    const token = store.getState().global.token;
    console.log("token", token);
    // 如果没有Token，跳转到登录页
    if (!token) {
        if (pathname !== "/login") {
            return <Navigate to="/login" replace />;
        } else {
            return props.children;
        }
        
    }

    if (pathname === "/login") {
        return <Navigate to="/loading" replace />;
    }

    
    // 获取动态路由DynamicRouter
    const dynamicRouter = store.getState().auth.authRouter;    
    // StaticRouter（静态路由）
    const staticRouter = ["/loading","/403","/404", "/401"];
    const routerList = [...dynamicRouter, ...staticRouter];
    if (!routerList.includes(pathname)) {
        // 如果没有权限，则跳转到403页面
        return <Navigate to="/403" replace />;
    }

    return props.children;
}

export default AuthRouter;